package com.bl.student.service.biz.id.impl;

import com.bl.student.common.utils.DateUtils;
import com.bl.student.common.utils.Generator;
import com.bl.student.dao.redis.IdDao;
import com.bl.student.service.biz.id.IdService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * Created by yujingyi on 2017/8/7.
 */
@Service
@Log4j2
public class IdServiceImpl implements IdService {

    @Autowired
    IdDao idDao;

    @Override
    public String getRandomNickname() {
        return Generator.generateRandomString().substring(0, 10);
    }

    public String getTradeNo() {
        String now = DateUtils.formatDate(new Date(), DateUtils.FORMAT_YYYYMMDDHHMMSS);
        long serialNum = idDao.incrAndGetIdSerialNum(now);
        while (serialNum > 99) {
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            now = DateUtils.formatDate(new Date(), DateUtils.FORMAT_YYYYMMDDHHMMSS);
            serialNum = idDao.incrAndGetIdSerialNum(now);
        }
        return (now + serialNum);
    }
}
